<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\Product\Type as TypeModel;
use app\common\validate\Product\Type as TypeValiDate;
use think\Exception;
use think\exception\ValidateException;

class Type extends BaseController
{
    protected $middleware = [
        \app\admin\middleware\LoginAuth::class
    ];
    public function index()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '商品分类'
        ];
        $searchfield = $this->request->param('search_field', 'name');
        $keyword = $this->request->param('keyword');
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "%$keyword%"];
        }
        // 每页显示数量
        $num = 8;
        $TypeList = TypeModel::where($where)->order('weigh', 'desc')->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $TypeList->currentPage();
        return view('', [
            'menu' => $menu,
            'TypeList' => $TypeList,
            'page' => $page,
            'num' => $num,
        ]);
    }
    // 新增商品分类
    public function add()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '新增商品分类'
        ];
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $data = [
                'name' => $param['name'],
                'weigh' => $param['weigh']
            ];
            $cover = upload('cover');
            if ($cover['code'] === 0) {
                $this->error($cover['msg']);
            }
            $data['cover'] = $cover['data'];
            // 验证数据的规则有无问题
            try {
                validate(TypeValiDate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }
            $result = TypeModel::create($data);
            if ($result === False) {
                $this->error('新增失败');
            }
            $this->success('新增成功', (string)url('/admin/type/index'));
        }
        return view('', [
            'menu' => $menu,
        ]);
    }
    // 删除分类
    public function del()
    {
        $typeid = $this->request->param('typeid');
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');
        if ($action == 'del') {
            $Type = TypeModel::find($typeid);
            if (!$Type) {
                $this->error('分类不存在');
            }
            $result = TypeModel::destroy($typeid);
            if ($result != false) {
                @is_file('.' . $Type['cover']) && @unlink('.' . $Type['cover']);
                $this->success('商品分类删除成功');
            } else {
                $this->error('商品分类删除失败');
            }
        }
        if ($action == 'dels') {
            $TypeList = TypeModel::whereIn('id', $ids)->select();
            foreach ($TypeList as $key => $item) {
                if (!in_array($item['id'], $ids)) {
                    $this->error("所选商品分类不存在,请重新选择");
                }
            }
            $result = TypeModel::destroy(['id' => $ids]);
            if ($result != false) {
                foreach ($TypeList as $key => $item) {
                    @is_file('.' . $item['cover']) && @unlink('.' . $item['cover']);
                }
                $this->success('商品分类删除成功');
            } else {
                $this->error('商品分类删除失败');
            }
        }
    }
    public function edit()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '编辑商品分类'
        ];
        $typeid = $this->request->param('typeid');
        $Type = TypeModel::find($typeid);
        if (!$Type) {
            $this->error('该商品分类不存在', (string)url('/admin/type/index'));
        }
        if ($this->request->isPost()) {
            try {
                $param = $this->request->param();
                $data = [
                    'name' => $param['name'],
                    'weigh' => $param['weigh']
                ];
                if (empty($param['name'])) {
                    throw new Exception('分类名称不能为空！');
                } else {
                    $name=TypeModel::where('id','<>',$typeid)->where(['name'=>$param['name']])->find();
                    if ($name) {
                        throw new Exception('该分类名称已存在，请重新填写');
                    }
                    $data['name'] = $param['name'];
                }
                if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                    $cover = upload('cover');
                    if ($cover['code'] === 0) {
                        throw new Exception($cover['msg']);
                    }
                    $data['cover'] = $cover['data'];
                }
                validate(TypeValiDate::class)->scene('edit')->check($data);
                $result = TypeModel::update($data, ['id' => $typeid]);
                if ($result === False) {
                    throw new Exception('修改失败');
                }
            } catch (ValidateException $e) {
                if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                    @is_file('.' . $data['cover']) && @unlink('.' . $data['cover']);
                }
                $this->error($e->getMessage());
            } catch (Exception $error) {
                if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                    @is_file('.' . $data['cover']) && @unlink('.' . $data['cover']);
                }
                $this->error($error->getMessage());
            }
            if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('.' . $Type['cover']) && @unlink('.' . $Type['cover']);
            }
            $this->success('修改成功', (string)url('/admin/type/index'));
        }
        return view('', [
            'menu' => $menu,
            'Type' => $Type
        ]);
    }
}
